package com.wn.base;

import cn.hutool.core.util.ObjectUtil;
import com.wn.base.algorithm.Person;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @FileName: Demo3
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/12/30 - 9:22
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class Demo3 {

    public static void main(String[] args) {
        Map<String, Object> map1 = new HashMap<>(8);
        Person person1 = new Person();
        map1.put("person", person1);
        System.out.println("person.id: " + ((Person) map1.get("person")).getId());
        byte[] bytes = ObjectUtil.serialize(map1);
        Map<String, Object> map2 = ObjectUtil.deserialize(bytes);
        Person person2 = (Person) map2.get("person");
        person2.setId("123");
        System.out.println("person.id: " + ((Person) map1.get("person")).getId());
        System.out.println(map1.get("person") == map2.get("person"));

    }

    public static <T> T cloneBySerializable(T obj) throws IOException, ClassNotFoundException {
        if (false == (obj instanceof Serializable)) {
            return null;
        }
        T cloneObj = null;
        try {
            // 将对象内容序列化
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.close();
            // 将对象反序列化
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            cloneObj = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            throw e;
        }
        return cloneObj;
    }

    // /**
    //  * map.putAll为浅拷贝测试
    //  * @param args
    //  */
    // public static void main(String[] args) {
    //     Map<String, Object> map1 = new HashMap<>(8);
    //     Map<String, Object> map2 = new HashMap<>(8);
    //     Person person1 = new Person();
    //     map1.put("person", person1);
    //     System.out.println("person.id: " + ((Person) map1.get("person")).getId());
    //
    //     map2.putAll(map1);
    //     Person person2 = (Person) map2.get("person");
    //     person2.setId("123");
    //     System.out.println("person.id: " + ((Person) map1.get("person")).getId());
    //     System.out.println(map1.get("person") == map2.get("person"));
    // }
}